﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraEditors;

namespace QL_Truong_Hoc.HocTap
{
    public partial class frmDSThiHetMon : DevExpress.XtraEditors.XtraForm
    {
        private const string mcstrRoleCode = "thi_cu";

        private int mintKdtID;
        private int mintLopID;
        private int mintMonID;
        private int mintThmID;

        private string mstrKhoa;
        private string mstrKhoas;
        private string mstrMon;
        private string mstrLop;
        private clsEnum.LAN_THI memLanThi;
        private bool mblnIsValid = false;

        private List<DevExpress.XtraGrid.StyleFormatCondition> mlstStyle;

        public frmDSThiHetMon()
        {
            InitializeComponent();
            mlstStyle = new List<DevExpress.XtraGrid.StyleFormatCondition>();
        }

        private void frmDSThiHetMon_Load(object sender, EventArgs e)
        {
            if (!clsCommon.fncCheckRole(Program.glstRoles, mcstrRoleCode))
            {
                this.BeginInvoke(new MethodInvoker(this.Close));
                return;
            }

            // TODO: This line of code loads data into the 'qLTHDataSet.mKhoa' table. You can move, or remove it, as needed.
            this.mKhoaTableAdapter.Fill(this.qLTHDataSet.mKhoa);
            // TODO: This line of code loads data into the 'qLTHDataSet.mGioiTinh' table. You can move, or remove it, as needed.
            this.mGioiTinhTableAdapter.Fill(this.qLTHDataSet.mGioiTinh);
            // TODO: This line of code loads data into the 'qLTHDataSet.mTrinhDoDaoTao' table. You can move, or remove it, as needed.
            this.mTrinhDoDaoTaoTableAdapter.Fill(this.qLTHDataSet.mTrinhDoDaoTao);
            // TODO: This line of code loads data into the 'qLTHDataSet.mMon' table. You can move, or remove it, as needed.
            this.mMonTableAdapter.Fill(this.qLTHDataSet.mMon);
            // TODO: This line of code loads data into the 'qLTHDataSet.mKhoaHoc' table. You can move, or remove it, as needed.
            this.mKhoaHocTableAdapter.Fill(this.qLTHDataSet.mKhoaHoc);
            // TODO: This line of code loads data into the 'qLTHDataSet.usrProc_GetThiHetMonFull' table. You can move, or remove it, as needed.
            this.usrProc_GetThiHetMonFullTableAdapter.Fill(this.qLTHDataSet.usrProc_GetThiHetMonFull);
            // TODO: This line of code loads data into the 'qLTHDataSet.mLop' table. You can move, or remove it, as needed.
            this.mLopTableAdapter.Fill(this.qLTHDataSet.mLop);
            // TODO: This line of code loads data into the 'qLTHDataSet.mLanThi' table. You can move, or remove it, as needed.
            this.mLanThiTableAdapter.Fill(this.qLTHDataSet.mLanThi);

            mlstStyle.Add(dgvDanhSachHocSinh.FormatConditions[0]);
            mlstStyle.Add(dgvDanhSachHocSinh.FormatConditions[1]);
        }

        private void mniAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                using (frmThiHetMonNghe frmThemMoi = new frmThiHetMonNghe())
                {
                    frmThemMoi.ShowDialog();
                    if (!frmThemMoi.Changed) return;

                    this.usrProc_GetThiHetMonFullTableAdapter.Fill(this.qLTHDataSet.usrProc_GetThiHetMonFull);
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnThemHs_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (mintThmID <= 0) return;

                bool blnSuccess = true;
                int intHsID;
                List<int> lstExcept = new List<int>();

                for (int i = 0; i <= dgvDanhSachHocSinh.RowCount - 1; i++)
                {
                    intHsID = clsCommon.fncCnvNullToInt(dgvDanhSachHocSinh.GetRowCellValue(i, colHS_ID));
                    lstExcept.Add(intHsID);
                }

                //if (mintMonID <= 0) return;
                using (frmChonHsThiHetMon frmChon = new frmChonHsThiHetMon(mintMonID, mintLopID, mintKdtID, lstExcept, mstrMon, mstrLop, memLanThi))
                {
                    frmChon.ShowDialog();
                    if (frmChon.DanhSachChon.Count <= 0) return;

                    //thêm vào danh sách
                    DTO.TThiHetMonHocSinhDTO objThiHetMon = new DTO.TThiHetMonHocSinhDTO();
                    objThiHetMon.THM_ID = mintThmID;

                    Program.gobjTrans = Program.gobjConn.BeginTransaction();

                    for (int i = 0; i <= frmChon.DanhSachChon.Count - 1; i++)
                    {
                        objThiHetMon.HS_ID = frmChon.DanhSachChon[i];
                        blnSuccess = blnSuccess && DAO.TThiHetMonHocSinhDAO.Insert(Program.gobjDb, Program.gobjTrans, objThiHetMon);
                    }

                    if (blnSuccess)
                    {
                        Program.gobjTrans.Commit();
                        this.usrProc_GetDanhSachThiHetMonTableAdapter.Fill(this.qLTHDataSet.usrProc_GetDanhSachThiHetMon, mintThmID);
                        dgvDanhSachHocSinh.BestFitColumns();
                    }
                    else
                    { Program.gobjTrans.Rollback(); }
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void grdControlDsDotThi_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (dgvDsDotThi.FocusedRowHandle < 0) return;

                mintKdtID = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colKDT_ID));
                mintLopID = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colLop_ID));
                mintMonID = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colMO_ID));
                mintThmID = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colTHM_ID));

                mstrKhoa = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colKH_ID));
                mstrKhoas = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colKHS_ID));
                mstrMon = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colMO_ID));
                mstrLop = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colLop_ID));
                memLanThi = (clsEnum.LAN_THI)clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colLanThi_ID));

                //ẩn cột điểm lần 2 nếu đang là lần 1
                if (memLanThi == clsEnum.LAN_THI.LAN_1)
                {
                    colHSM_diemketthucmodulelan2.Visible = false;
                    dgvDanhSachHocSinh.FormatConditions.Clear();
                    dgvDanhSachHocSinh.FormatConditions.Add(mlstStyle[0]);
                }
                else
                {
                    colHSM_diemketthucmodulelan2.Visible = true;
                    dgvDanhSachHocSinh.FormatConditions.Clear();
                    dgvDanhSachHocSinh.FormatConditions.Add(mlstStyle[1]);
                }

                this.usrProc_GetDanhSachThiHetMonTableAdapter.Fill(this.qLTHDataSet.usrProc_GetDanhSachThiHetMon, mintThmID);
                dgvDanhSachHocSinh.BestFitColumns();

                grpDanhSachThiSinh.Text = "Danh sách thí sinh thi hết môn " + mstrMon + " - lớp " + mstrLop + " - khóa " + mstrKhoas + " - khoa " + mstrKhoa;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnSuaDiem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                dgvDanhSachHocSinh.FocusedRowHandle = 0;

                switch (memLanThi)
                {
                    case clsEnum.LAN_THI.LAN_1:
                        colHSM_diemketthucmodulelan1.OptionsColumn.AllowEdit = true;
                        dgvDanhSachHocSinh.FocusedColumn = colHSM_diemketthucmodulelan1;
                        //dgvDanhSachHocSinh.SelectCells(0, colHSM_diemketthucmodulelan1, 0, colHSM_diemketthucmodulelan1);
                        break;
                    case clsEnum.LAN_THI.LAN_2:
                        colHSM_diemketthucmodulelan2.OptionsColumn.AllowEdit = true;
                        dgvDanhSachHocSinh.FocusedColumn = colHSM_diemketthucmodulelan2;
                        //dgvDanhSachHocSinh.SelectCells(0, colHSM_diemketthucmodulelan2, 0, colHSM_diemketthucmodulelan2);
                        break;
                }
                dgvDanhSachHocSinh.ShowEditor();
                btnHuyDiem.Enabled = true;
                btnXoaHocSinh.Enabled = false;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnLuuDiem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (!mblnIsValid) return;

                float fltDiem;
                int intHsID;
                bool blnSuccess = true;
                DTO.THocSinhMonDTO objHsMon;
                List<DTO.THocSinhMonDTO> lstHsMon;

                btnHuyDiem.Enabled = false;
                btnXoaHocSinh.Enabled = true;
                lstHsMon = new List<DTO.THocSinhMonDTO>();

                //lấy danh sách hs trc
                for (int i = 0; i <= dgvDanhSachHocSinh.RowCount - 1; i++)
                {
                    objHsMon = new DTO.THocSinhMonDTO();

                    intHsID = clsCommon.fncCnvNullToInt(dgvDanhSachHocSinh.GetRowCellValue(i, colHS_ID));
                    objHsMon = DAO.THocSinhMonDAO.Select(Program.gobjDb, intHsID, mintMonID);

                    switch (memLanThi)
                    {
                        case clsEnum.LAN_THI.LAN_1:
                            fltDiem = clsCommon.fncCnvNullToFloat(dgvDanhSachHocSinh.GetRowCellValue(i, colHSM_diemketthucmodulelan1));
                            objHsMon.HSM_diemketthucmodulelan1 = fltDiem;
                            break;
                        case clsEnum.LAN_THI.LAN_2:
                            fltDiem = clsCommon.fncCnvNullToFloat(dgvDanhSachHocSinh.GetRowCellValue(i, colHSM_diemketthucmodulelan2));
                            objHsMon.HSM_diemketthucmodulelan2 = fltDiem;
                            break;
                    }

                    lstHsMon.Add(objHsMon);
                }

                Program.gobjTrans = Program.gobjConn.BeginTransaction();

                for (int i = 0; i <= lstHsMon.Count - 1; i++)
                {
                    //thuc hien update
                    blnSuccess = blnSuccess && DAO.THocSinhMonDAO.Update(Program.gobjDb, Program.gobjTrans, lstHsMon[i]);
                }

                if (blnSuccess)
                {
                    Program.gobjTrans.Commit();
                }
                else
                {
                    clsCommon.fncMsgError("Cập nhật thất bại. Xin hãy thử lại.");
                    Program.gobjTrans.Rollback();
                }

                switch (memLanThi)
                {
                    case clsEnum.LAN_THI.LAN_1:
                        colHSM_diemketthucmodulelan1.OptionsColumn.AllowEdit = false;
                        break;
                    case clsEnum.LAN_THI.LAN_2:
                        colHSM_diemketthucmodulelan2.OptionsColumn.AllowEdit = false;
                        break;
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
            finally { Cursor.Current = Cursors.Default; }
        }

        private void btnXoaHocSinh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (dgvDanhSachHocSinh.FocusedRowHandle <= 0) return;

                string strHodem = clsCommon.fncCnvNullToString(dgvDanhSachHocSinh.GetFocusedRowCellValue(colhs_hodem));
                string strTen = clsCommon.fncCnvNullToString(dgvDanhSachHocSinh.GetFocusedRowCellValue(colhs_ten));

                strTen = strHodem + " " + strTen;

                if (!clsCommon.fncMsgConfirm("Bạn có chắc muốn loại thí sinh " + strTen + " khỏi danh sách?")) return;

                int intHsID;

                intHsID = clsCommon.fncCnvNullToInt(dgvDanhSachHocSinh.GetFocusedRowCellValue(colHS_ID));

                if (!DAO.TThiHetMonHocSinhDAO.Delete(Program.gobjDb, Program.gobjTrans, mintThmID, intHsID))
                {
                    //xóa thất bại
                    clsCommon.fncMsgError("Xóa thất bại. Xin hãy thử lại.");
                    return;
                }
                else
                {
                    dgvDanhSachHocSinh.DeleteSelectedRows();
                }

            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnHuyDiem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                btnHuyDiem.Enabled = false;
                btnXoaHocSinh.Enabled = true;
                this.usrProc_GetDanhSachThiHetMonTableAdapter.Fill(this.qLTHDataSet.usrProc_GetDanhSachThiHetMon, mintThmID);
                dgvDanhSachHocSinh.BestFitColumns();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void dgvDanhSachHocSinh_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            try
            {
                string strFieldName = "";

                switch (memLanThi)
                {
                    case clsEnum.LAN_THI.LAN_1:
                        strFieldName = "HSM_diemketthucmodulelan1";
                        break;
                    case clsEnum.LAN_THI.LAN_2:
                        strFieldName = "HSM_diemketthucmodulelan2";
                        break;
                }

                float fltDiem = 0.0F;

                if (!float.TryParse(dgvDanhSachHocSinh.GetRowCellValue(e.RowHandle, strFieldName).ToString(), out fltDiem))
                {
                    e.Valid = false;
                    dgvDanhSachHocSinh.SetColumnError(dgvDanhSachHocSinh.Columns[strFieldName], "Điểm không hợp lệ.");
                    mblnIsValid = false;
                    return;
                }

                if (fltDiem < 0 || fltDiem > 10)
                {
                    e.Valid = false;
                    dgvDanhSachHocSinh.SetColumnError(dgvDanhSachHocSinh.Columns[strFieldName], "Điểm không hợp lệ.");
                    mblnIsValid = false;
                    return;
                }

                mblnIsValid = true;

            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void dgvDanhSachHocSinh_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            try
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnXuatDanhSach_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if(mintThmID <=0 )return;

                Cursor.Current = Cursors.WaitCursor;

                Export.frmExportExcel objForm = new Export.frmExportExcel();
                Export.clsDSKiemTraKetThucMonNghe.stSetting stOption = new Export.clsDSKiemTraKetThucMonNghe.stSetting();

                //tạo dữ liệu
                stOption.strKhoa = mstrKhoa;
                stOption.strKhoas = mstrKhoas;
                stOption.strLop = mstrLop;
                stOption.strMon = mstrMon;

                if (!objForm.fncExportDanhSachThiHetMonNghe(stOption, this.qLTHDataSet.usrProc_GetDanhSachThiHetMon) ) return;
                objForm.MdiParent = this.MdiParent;
                objForm.Show();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
    }
}